package org.fuxia.im.core.service.impl;

import javax.annotation.Resource;

import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.db.dao.UserDaoImpl;
import org.fuxia.im.db.dao.UserFriendDaoImpl;
import org.fuxia.im.entities.User;

public class UserService extends AbstractService{

	@Resource
	private UserDaoImpl userDao ;
	
	@Resource
	private UserFriendDaoImpl ufDao ;
	
	public void service(ECPacket packet) {
		String option = packet.getParameter("option") ;
		if("modify".equals(option)) {
			modify(packet) ;
		}else if("delUser".equals(option)) {
			delUser(packet) ;
		}
	}
	
	/**
	 * 删除好友
	 * @param packet
	 */
	private void delUser(ECPacket packet) {
		String userCode= packet.getParameter("del_user_code") ;
		String from = packet.getFrom() ;
		String hql = "delete from UserFriend uf where uf.orignUserCode='%s' and uf.friendUserCode='%s'" ;
		ECResponse resp = new ECResponse() ;
		resp.setResponseType("DEL_USER") ;
		try{
			ufDao.bulkUpdate(String.format(hql, from,userCode));
			resp.put("friendUserCode", userCode);
			resp.setResponseText("删除好友成功") ;
			resp.put("groupKey", packet.getParameter("groupKey"));
		}catch (Exception e) {
			resp.setStatusCode(400);
			resp.setResponseText("删除好友失败");
		}
		writeReponse(packet, resp) ;
		
	}
	
	
	public void modify(ECPacket packet) {
		
		String userCode = packet.getParameter("userCode") ;
		User temp = userDao.getByPK(userCode) ;
		
		ECResponse resp = new ECResponse() ;
		
		User user = new User() ;
		user.setUserCode(userCode) ;
		user.setNickName(packet.getParameter("nickName")) ;
		user.setPersonNote(packet.getParameter("personNode")) ;
		user.setSex(packet.getParameter("sex")) ;
		user.setAge(Integer.getInteger(packet.getParameter("age"))) ;
		user.setBirthDay(packet.getParameter("birthday")) ;
		user.setZipcode(packet.getParameter("zipcode")) ;
		user.setAddress(packet.getParameter("address")) ;
		user.setImagePath(packet.getParameter("imagePath")) ;
		user.setIsDiable(temp.getIsDiable()) ;
		user.setCreateDate(temp.getCreateDate()) ;
		user.setPassword(temp.getPassword()) ;
		user.setIdCard(temp.getIdCard()) ;
		
		resp.setResponseType("MODOFY_USER") ;
		try{
			userDao.merge(user) ;
			resp.setStatusCode(200) ;
		}catch(Exception e) {
			e.printStackTrace() ;
			resp.setStatusCode(400) ;
			resp.setResponseText("更新个人资料失败！") ;
		}
		try{
			writeReponse(packet, resp) ;
		}catch(Exception e) {
			e.printStackTrace() ;
		}
		
	} 

}
